<template>
  <div id="syslog">
    <div class="syslog-info">
      <h3 class="top-title">{{ $t('ALARM_REPORT_SYSLOG_FUNC') }}</h3>
      <el-form :model="formSyslog" label-width="auto" label-position="left">
        <!-- syslog使能 -->
        <el-form-item
          id="syslogStateItem"
          :label="$t('ALARM_REPORT_SYSLOG_ENABLE')"
          class="small-item"
        >
          <el-switch
            id="syslogState"
            v-model="formSyslog.state"
            :disabled="isSystemLock || !hasSecurityConfigPrivil"
            @change="stateChange"
          ></el-switch>
        </el-form-item>
        <!-- 告警级别 -->
        <el-form-item id="syslogAlarmLevelItem" :label="$t('ALARM_EVENT_ALARM_LEVEL')">
          <el-select
            v-model="formSyslog.alarmLevel.value"
            v-addId.select="'syslogAlarmLevel'"
            :disabled="isSystemLock || !hasSecurityConfigPrivil"
            :teleported="false"
            :suffix-icon="PullDownTriangle"
            @change="alarmLevelChange"
          >
            <el-option
              v-for="item in formSyslog.alarmLevel.options"
              :key="item.id"
              :label="item.key"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- syslog消息格式 -->
        <el-form-item
          id="syslogMessageFormatItem"
          :label="$t('ALARM_REPORT_SYSLOG_MESSAGE_FORMAT')"
        >
          <el-select
            v-model="formSyslog.messageFormat.value"
            v-addId.select="'syslogMessageFormat'"
            :disabled="isSystemLock || !hasSecurityConfigPrivil"
            :teleported="false"
            :suffix-icon="PullDownTriangle"
            @change="messageFormatChange"
          >
            <el-option
              v-for="item in formSyslog.messageFormat.options"
              :key="item.id"
              :label="item.key"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- syslog主机标识 -->
        <el-form-item id="syslogFlagItem" :label="$t('ALARM_REPORT_SYSLOG_FLAG')">
          <el-select
            v-model="formSyslog.syslogFlag.value"
            v-addId.select="'syslogFlag'"
            :disabled="
              formSyslog.messageFormat.value === 'RFC3164' ||
                isSystemLock ||
                !hasSecurityConfigPrivil
            "
            :teleported="false"
            :suffix-icon="PullDownTriangle"
            @change="syslogFlagChange"
          >
            <el-option
              v-for="item in formSyslog.syslogFlag.options"
              :key="item.id"
              :label="item.key"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 传输协议 -->
        <el-form-item
          id="syslogProtocolItem"
          :label="$t('ALARM_REPORT_SYSLOG_PROTOCOL')"
          class="small-item"
        >
          <el-radio-group
            v-model="formSyslog.protocol.value"
            :disabled="isSystemLock || !hasSecurityConfigPrivil"
            @change="protocolChange"
          >
            <el-radio
              v-for="item in formSyslog.protocol.list"
              :id="'syslog' + item.id"
              :key="item.id"
              :label="item.key"
            ></el-radio>
          </el-radio-group>
          <span v-if="formSyslog.protocol.value !== 'TLS'" id="syslogAlert">
            {{ $t(warningTip) }}
          </span>
        </el-form-item>
        <!-- 认证方式 -->
        <el-form-item
          v-if="formSyslog.protocol.value === 'TLS'"
          id="syslogAuthModeItem"
          :label="$t('ALARM_REPORT_SYSLOG_AUTHOR')"
          class="small-item"
        >
          <el-radio-group
            v-model="formSyslog.authMode.value"
            :disabled="isSystemLock || !hasSecurityConfigPrivil"
            @change="authModeChange"
          >
            <el-radio
              v-for="item in formSyslog.authMode.list"
              :id="'syslog' + item.id"
              :key="item.id"
              :label="item.id"
            >
              {{ $t(item.key) }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 告警类型 -->
        <el-form-item
          id="syslogAlarmType"
          :label="$t('ALARM_REPORT_SYSLOG_ALARM_TYPE')"
          class="small-item"
        >
          <el-radio-group
            v-model="formSyslog.alarmType.value"
            :disabled="isSystemLock || !hasSecurityConfigPrivil"
            @change="alarmTypeChange"
          >
            <el-radio
              v-for="item in formSyslog.alarmType.list"
              :id="'syslog' + item.id"
              :key="item.id"
              :label="item.id"
            >
              {{ $t(item.key) }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 服务器根证书 -->
        <el-form-item
          v-if="formSyslog.protocol.value === 'TLS'"
          id="syslogCerItem"
          class="cer-item"
          :label="$t('ALARM_REPORT_SYSLOG_SERVICE_ROOT_AUTH')"
        >
          <CertificateRedirect
            ref="redirectComp"
            :need-save="!syslogBtn && !isSystemLock"
            message="CERTIFICATE_TO_CA"
            @callback="saveBtn(1)"
            @redirect="redirect()"
          />
        </el-form-item>
        <!-- 本地证书 -->
        <el-form-item
          v-if="formSyslog.protocol.value === 'TLS' && formSyslog.authMode.value === 'TwoWay'"
          id="localCer"
          class="cer-item"
          :label="$t('ALARM_REPORT_SYSLOG_SERVICE_LOCAL_AUTH')"
        >
          <CertificateRedirect
            ref="redirectSslComp"
            :need-save="!syslogBtn && !isSystemLock"
            message="CERTIFICATE_TO_SSL"
            @callback="saveBtn(2)"
            @redirect="redirectSsl()"
          />
        </el-form-item>
        <el-form-item class="syslog-btns" :label="' '">
          <el-button
            id="syslogSaveBtn"
            :disabled="syslogBtn || isSystemLock"
            type="primary"
            @click="saveBtn(0)"
          >
            {{ $t('COMMON_SAVE') }}
          </el-button>
          <el-button v-show="!syslogBtn" id="syslogCancelBtn" @click="syslogCancelFun">
            {{ $t('COMMON_CANCEL') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="syslogTableBox" class="syslog-syntax">
      <h3 id="syslogTableTitle" class="table-title">{{ $t('ALARM_REPORT_SYSLOG_TITLE') }}</h3>
      <SyslogTable
        :data="srcData.data"
        :is-system-lock="isSystemLock"
        :has-permission="hasSecurityConfigPrivil"
        @operate-change="tableChange"
      ></SyslogTable>
    </div>
    <div v-if="dialogVisible" v-reqKeepAlive.dialog>
      <el-dialog
        :id="dialogConfig.id"
        v-model="dialogVisible"
        :title="dialogConfig.title"
        width="30%"
      >
        <div>
          <el-form label-width="auto">
            <el-form-item :label="$t('ALARM_REPORT_SYSLOG_CER_FILE')" class="cer-file-upload">
              <el-input
                v-model="fileName"
                readonly="true"
                clearable
                @change="fileChange"
              ></el-input>
              <el-upload
                id="uploadx"
                ref="cerUploadRef"
                class="upload-root-cer"
                :action="cer.url"
                :accept="cer.accept"
                :auto-upload="cer.autoUpload"
                :show-file-list="false"
                :on-change="cer.addItemChange"
                :on-remove="cer.removeItems"
              >
                <span>...</span>
              </el-upload>
              <div v-if="isAddFileError" id="syslogFailed" class="pwdError">
                {{ $t(errorTips) }}
              </div>
            </el-form-item>
            <el-form-item id="cerPwdItem" :label="$t('SERVICE_WBS_DLOG_CRE_PWD')">
              <el-input
                id="cerPwd"
                v-model="cer.value"
                :placeholder="cer.tip"
                type="password"
                size="normal"
                clearable
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <span>
            <el-button
              id="cerSaveBtn"
              type="primary"
              :disabled="uploadBtnDisable"
              @click="cer.save"
            >
              {{ $t('ALARM_OK') }}
            </el-button>
            <el-button id="cerCancelBtn" @click="cer.cencel">{{ $t('ALARM_CANCEL') }}</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
  <Dialog ref="commonDialogRef" :config="commonDialogConfig" @close="commonDialogClose" />
</template>

<script lang="ts" setup>
import { getErrorTranslate, traduction } from '@/utils/language';
import { UploadRawFile, UploadFile } from 'element-plus/es/components/upload/src/upload';
import { computed, onMounted, reactive, ref } from 'vue';
import {
  alertMessage,
  getSyslogInfo,
  imporCustomCertificate,
  sysLogSave,
  sysLogSendTest,
} from '../report.service';
import { getMessageId, escapeHeader } from '@/utils/utils';
import SyslogCertificate from './SyslogCertificate.vue';
import SyslogTable from './SyslogTable.vue';
import { ElMessageBox } from 'element-plus';
import GlobalStoreService from '@/services/gloabal-store-service';
import useStore from '@/stores';
import { loading, showFailedMessage, showSuccessMessage, getStoreData } from '@/utils/composition';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';
import PullDownTriangle from '@/components/PullDownTriangle/PullDownTriangle.vue';
import { useRouter } from 'vue-router';
import CertificateRedirect from '@/pages/User/Certificate/CertificateRedirect.vue';

const redirectComp = ref();
const redirectSslComp = ref();
const $router = useRouter();
const store = useStore();
let isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const isSyslog = computed(() => getStoreData('loct', 'syslog'));
const warningTip = ref('ALARM_REPORT_SYSLOG_TLS');
const cerUploadRef = ref();
const hasSecurityConfigPrivil = checkPrivil(UserPrivil.securityConfig);
const globalStoreService = new GlobalStoreService();
const dialogRef = ref();
const commonDialogRef = ref();
const dialogVisible = ref(false);
const dialogConfig = reactive({
  title: traduction('COMMON_CER_UPLOAD'),
  id: 'uploadDialog',
});
const commonDialogConfig = reactive({
  id: 'syslogTestModel',
  content: traduction('ALARM_REPORT_SYSLOG_TEST'),
  title: traduction('COMMON_CONFIRM'),
  cancelButton: {
    hide: true,
  },
});
const formSyslog = reactive({
  state: false,
  alarmLevel: {
    value: 'Normal',
    options: [
      {
        id: 'None',
        key: '[NULL]',
      },
      {
        id: 'Critical',
        key: traduction('ALARM_EVENT_CRITICAL'),
      },
      {
        id: 'Major',
        key: traduction('ALARM_EVENT_MAJOR'),
      },
      {
        id: 'Minor',
        key: traduction('ALARM_EVENT_MINOR'),
      },
      {
        id: 'Normal',
        key: traduction('ALARM_EVENT_NORMAL'),
      },
    ],
  },
  messageFormat: {
    value: 'Custom',
    options: [
      {
        id: 'Custom',
        key: traduction('SERVICE_WBS_CRE_CUSTOM'),
      },
      {
        id: 'RFC3164',
        key: 'RFC3164',
      },
    ],
  },
  syslogFlag: {
    value: 'BoardSN',
    options: [
      {
        id: 'BoardSN',
        key: traduction('ALARM_REPORT_EMAIL_SUBJECT_1'),
      },
      {
        id: 'ProductAssetTag',
        key: traduction('ALARM_REPORT_EMAIL_SUBJECT_2'),
      },
      {
        id: 'HostName',
        key: traduction('ALARM_REPORT_EMAIL_SUBJECT_3'),
      },
    ],
  },
  protocol: {
    value: 'TLS',
    list: [
      {
        id: 'TLS',
        key: 'TLS',
      },
      {
        id: 'TCP',
        key: 'TCP',
      },
      {
        id: 'UDP',
        key: 'UDP',
      },
    ],
  },
  authMode: {
    value: 'OneWay',
    list: [
      {
        id: 'OneWay',
        key: 'ALARM_REPORT_SYSLOG_AUTHOR_SINGLE',
      },
      {
        id: 'TwoWay',
        key: 'ALARM_REPORT_SYSLOG_AUTHOR_DOUBLE',
      },
    ],
  },
  alarmType: {
    value: 'OemEvent',
    list: [
      {
        id: 'OemEvent',
        key: 'ALARM_REPORT_SYSLOG_ALARM_EVENT',
      },
      {
        id: 'SEL',
        key: 'ALARM_REPORT_SYSLOG_ALARM_SEL',
      },
    ],
  },
});
let response: syslogType;
function stateChange(val: boolean) {
  changeBtnStatus();
}
// 告警级别change事件
function alarmLevelChange(val: string) {
  changeBtnStatus();
}
// syslog消息格式change事件
function messageFormatChange(val: string) {
  changeBtnStatus();
}
// syslog主机标识change事件
function syslogFlagChange(val: string) {
  changeBtnStatus();
}
// 传输协议change事件
function protocolChange(val: string) {
  changeBtnStatus();
}
// 告警类型change事件
function alarmTypeChange(val: string) {
  changeBtnStatus();
}
// 认证方式change事件
function authModeChange(val: string) {
  changeBtnStatus();
}
function changeBtnStatus() {
  const isEqual =
    formSyslog.state === defaultData.EnableState &&
    formSyslog.protocol.value === defaultData.TransmissionProtocol &&
    formSyslog.authMode.value === defaultData.AuthenticateMode &&
    formSyslog.alarmLevel.value === defaultData.AlarmSeverity &&
    formSyslog.alarmType.value === defaultData.ReportType &&
    formSyslog.syslogFlag.value === defaultData.ServerIdentity &&
    formSyslog.messageFormat.value === defaultData.MessageFormat;
  if (isEqual) {
    syslogBtn.value = true;
  } else {
    syslogBtn.value = false;
  }
}
// 保存上面的数据
function saveBtn(redirectType: number) {
  const saveParam = {};
  if (formSyslog.state !== defaultData.EnableState) {
    saveParam['EnableState'] = formSyslog.state;
  }
  if (formSyslog.protocol.value !== defaultData.TransmissionProtocol) {
    saveParam['TransmissionProtocol'] = formSyslog.protocol.value;
  }
  if (formSyslog.authMode.value !== defaultData.AuthenticateMode) {
    saveParam['AuthenticateMode'] = formSyslog.authMode.value;
  }
  if (formSyslog.alarmLevel.value !== defaultData.AlarmSeverity) {
    saveParam['AlarmSeverity'] = formSyslog.alarmLevel.value;
  }
  if (
    formSyslog.syslogFlag.value !== defaultData.ServerIdentity &&
    formSyslog.messageFormat.value !== 'RFC3164'
  ) {
    saveParam['ServerIdentity'] = formSyslog.syslogFlag.value;
  }
  if (formSyslog.messageFormat.value !== defaultData.MessageFormat) {
    saveParam['MessageFormat'] = formSyslog.messageFormat.value;
  }
  if (formSyslog.alarmType.value !== defaultData.ReportType) {
    saveParam['ReportType'] = formSyslog.alarmType.value;
  }
  // 不为空
  if (JSON.stringify(saveParam) === '{}') {
    getInfo();
    return;
  }
  sysLogSave(saveParam).then(
    res => {
      showSuccessMessage();
      getInfo();
      syslogBtn.value = true;
      callbackSuccess(redirectType);
    },
    error => {
      showFailedMessage();
      syslogBtn.value = false;
      callbackFail(redirectType);
    },
  );
}

let defaultData: any;
// 根证书
const oneWayInfo = reactive({
  issuer: '',
  subject: '',
  validNotBefore: '',
  validNotAfter: '',
  serialNumber: '',
  crlState: false,
  listTime: '',
  crlURL: '',
});
// 客户端证书
const twoWayInfo = reactive({
  issuer: '',
  subject: '',
  validNotBefore: '',
  validNotAfter: '',
  serialNumber: '',
});
const showRoot = ref(false);
const showClient = ref(false);
const syslogCancel = ref(false);
const syslogBtn = ref(true);
const srcData = reactive({
  data: <any[]>[],
});
interface syslogServerList {
  ID: string;
  IP: string;
  Enabled: boolean;
  Port: number;
  LogType: any;
}
function _setLogTypeSelect(arr: []) {
  if (arr.length === 0) {
    return;
  }
  let result = '';
  arr.forEach(item => {
    
    result += _filterLogType(item) + ' + '; 
  });
  return result.slice(0, -2);
}
function _filterLogType(type: string) {
  let zh = '';
  switch (type) {
    case 'OperationLog':
      zh = traduction('OPERATE_LOG');
      break;
    case 'SecurityLog':
      zh = traduction('SERCURITY_LOG');
      break;
    case 'EventLog':
      zh = traduction('EVENT_LOG');
      break;
    case 'IntrusionDetectionLog':
      zh = traduction('INTRUSION_DETECTION_LOG');
      break;
    case 'SysComLog':
      zh = traduction('SYS_COM_LOG');
      break;
    case 'BmcComLog':
      zh = traduction('BMC_COM_LOG');
      break;
    case 'DiagnosticLog':
      zh = traduction('DIAGNOSTIC_LOG');
      break;
    case 'ChipLog':
      zh = traduction('CHIP_LOG');
      break;
    default:
      zh = traduction('OPERATE_LOG');
      break;
  }
  return zh;
}
interface syslogType {
  AlarmSeverity: string;
  AuthenticateMode: string;
  EnableState: boolean;
  MessageFormat: string;
  RootCertificate?: any;
  ClientCertificate?: any;
  ServerIdentity: string;
  SyslogServerList: any[];
  TransmissionProtocol: string;
  ReportType: string;
}
function setRootCertificate(response: syslogType) {
  oneWayInfo.issuer = response.RootCertificate.Issuer;
  oneWayInfo.subject = response.RootCertificate.Subject;
  oneWayInfo.validNotBefore = response.RootCertificate.ValidNotBefore;
  oneWayInfo.validNotAfter = response.RootCertificate.ValidNotAfter;
  oneWayInfo.serialNumber = response.RootCertificate.SerialNumber;
  oneWayInfo.crlState = response.RootCertificate.CrlVerificationEnabled;
  if (response.RootCertificate.CrlValidFrom && response.RootCertificate.CrlValidTo) {
    oneWayInfo.listTime = `${response.RootCertificate.CrlValidFrom} - ${response.RootCertificate.CrlValidTo}`;
  } else {
    oneWayInfo.listTime = '--';
  }
  showRoot.value = true;
}
function setClientCertificate(response: syslogType) {
  twoWayInfo.issuer = response.ClientCertificate.Issuer;
  twoWayInfo.subject = response.ClientCertificate.Subject;
  twoWayInfo.validNotBefore = response.ClientCertificate.ValidNotBefore;
  twoWayInfo.validNotAfter = response.ClientCertificate.ValidNotAfter;
  twoWayInfo.serialNumber = response.ClientCertificate.SerialNumber;
  showClient.value = true;
}
function setTableData(response: syslogType) {
  const data: any[] = [];
  response.SyslogServerList.forEach((item: syslogServerList, idx: any) => {
    const obj = {};
    obj['num'] = Number(item.ID) + 1;
    obj['serviceAddr'] = item.IP;
    obj['statusValue'] = item.Enabled;
    obj['port'] = item.Port === 0 ? null : item.Port;
    obj['LogType'] = setLog();
    _setChecked(obj['LogType'], item.LogType);
    obj['isEdit'] = false;
    obj['itemSelect'] = _setLogTypeSelect(item.LogType);
    obj['validationAddr'] = {
      tip: traduction('COMMON_IPV4_IPV6_TLS_DOMIN'),
      tipPosition: 'right',
      errorMessage: {
        pattern: traduction('COMMON_FORMAT_ERROR'),
      },
    };
    obj['validationPort'] = {
      tip: traduction('VALIDTOR_RANGE'),
      tipPosition: 'right',
      errorMessage: {
        number: traduction('ALARM_REPORT_RANGESIZE'),
        digits: traduction('ALARM_REPORT_RANGESIZE'),
        rangeValue: traduction('ALARM_REPORT_RANGESIZE'),
      },
    };
    obj['type'] = defaultData.TransmissionProtocol;
    if (obj['port']) {
      obj['canSave'] = true;
    } else {
      obj['canSave'] = false;
    }
    obj['disabled'] = false;
    data.push(obj);
  });
  srcData.data = data;
}
function getInfo() {
  globalStoreService.setValue('isLoading', true);
  getSyslogInfo()
    .then(res => {
      defaultData = res['data'];
      response = res['data'] as syslogType;
      init(response);

      // 有表格数据
      if (
        response.SyslogServerList &&
        response.SyslogServerList.length > 0 &&
        !syslogCancel.value
      ) {
        setTableData(response);
      }
      syslogCancel.value = false;
      syslogBtn.value = true;
      globalStoreService.setValue('isLoading', false);
    })
    .catch(() => {
      globalStoreService.setValue('isLoading', false);
    });
}
function init(response: syslogType) {
  formSyslog.state = response.EnableState;
  formSyslog.protocol.value = response.TransmissionProtocol;
  formSyslog.authMode.value = response.AuthenticateMode;
  formSyslog.alarmLevel.value = response.AlarmSeverity;
  formSyslog.messageFormat.value = response.MessageFormat;
  formSyslog.syslogFlag.value = response.ServerIdentity;
  formSyslog.alarmType.value = response.ReportType;

  if (isSyslog?.value?.ProtocolSupported?.RELP) {
    if (formSyslog.protocol.list.length === 3) {
      formSyslog.protocol.list.push({
        id: 'RELP',
        key: 'RELP',
      })
    }
    warningTip.value = 'ALARM_REPORT_SYSLOG_RELP';
  }

  if (response.RootCertificate) {
    setRootCertificate(response);
  } else {
    showRoot.value = false;
  }
  if (response.ClientCertificate) {
    setClientCertificate(response);
  } else {
    showClient.value = false;
  }
}
function syslogCancelFun() {
  init(response);
  syslogBtn.value = true;
}
// 吊销证书上传结果
function saveLog() {
  const saveParam = {};
  if (defaultData.TransmissionProtocol !== formSyslog.protocol.value) {
    saveParam['TransmissionProtocol'] = formSyslog.protocol.value;
  }
  if (defaultData.AuthenticateMode !== formSyslog.authMode.value) {
    saveParam['AuthenticateMode'] = formSyslog.authMode.value;
  }
  if (JSON.stringify(saveParam) !== '{}') {
    sysLogSave(saveParam).then(res => {
      getInfo();
    });
  } else {
    getInfo();
  }
}
const loct = localStorage.getItem('loct');
// 根证书上传
const rootUpload = reactive({
  url: '/UI/Rest/Maintenance/SyslogNotification/ImportRootCertificate',
  headers: {
    From: 'WebUI',
    'X-CSRF-Token': escapeHeader(loct ? JSON.parse(loct).to : ''),
  },
  method: 'POST',
  accept: '.crt,.cer,.pem',
  isAutoUpload: true,
  name: 'Content',
  successItems: (data: UploadFile) => {
    showSuccessMessage();
    getInfo();
    saveLog();
  },
  errorItems: () => {
    showFailedMessage();
  },
  beforeUpload: (rawFile: UploadRawFile): void | boolean => {
    let type = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1);
    if (!['crt', 'cer', 'pem'].includes(type)) {
      showFailedMessage(traduction('COMMON_FILE_SUFFIX_CER_PEM_CRT'));
      return false;
    } else if ((rawFile.size as any) > 100 * 1024) {
      showFailedMessage(traduction('COMMON_UPLOAD_FILE_MORN_100KB_ERROR4'));
      return false;
    }
  },
});
const isAddFileError = ref(false);
const uploadBtnDisable = ref(true);
const fileName = ref('');
let fileRaw: UploadRawFile | undefined;
const errorTips = ref('');
// 本地证书上传
const cer = reactive({
  label1: 'ALARM_REPORT_SYSLOG_CER_FILE',
  label2: 'SERVICE_WBS_DLOG_CRE_PWD',
  tip: traduction('ALARM_REPORT_SYSLOG_CER_TIP'),
  value: '',
  url: '',
  accept: '.pfx,.p12',
  autoUpload: false,
  removeItems: () => {
    isAddFileError.value = false;
    uploadBtnDisable.value = true;
  },
  addItemChange: (file: UploadFile) => {
    const type = file.name.substring(file.name.lastIndexOf('.'));
    if (file.status === 'ready') {
      if (!['.pfx', '.p12'].includes(type)) {
        showFailedMessage(traduction('IBMC_UPLOAD_FILE_TYPE'));
      } else if ((file.size as any) > 1024 * 1024) {
        showFailedMessage(traduction('IBMC_UPLOAD_FILE_1M_ERROR3'));
      } else {
        fileRaw = file.raw;
        fileName.value = file.name;
        isAddFileError.value = true;
        uploadBtnDisable.value = false;
      }
    }
  },
  save: () => {
    if (fileRaw) {
      sysLogClientCertificate(fileRaw, fileName.value);
    }
    clearFiles();
  },
  cencel: () => {
    clearFiles();
  },
});
function clearFiles() {
  dialogVisible.value = false;
  cerUploadRef.value.clearFiles();
  cer.value = '';
}
function sysLogClientCertificate(file: any, fileName: string) {
  const clientFormData = new FormData();
  clientFormData.append('Content', file, fileName);
  if (cer.value) {
    clientFormData.append('Password', cer.value);
  }
  imporCustomCertificate(clientFormData, {
    headers: {
      From: 'WebUI',
      Accept: '*/*',
      'X-CSRF-Token': escapeHeader(loct ? JSON.parse(loct).to : ''),
    },
  })
    .then(() => {
      showSuccessMessage();
      clearFiles();
      saveLog();
      getInfo();
    })
    .catch(error => {
      const errors = getMessageId(error.data);
      if (error && errors?.length > 0) {
        const errorId = errors[0].code;
        if (errorId?.includes('EncryptionAlgorithmIsWeak')) {
          showFailedMessage(traduction('ALARM_REPORT_SYSLOG_MD5_CARD_FAILED'));
        } else {
          const errorMsg = getErrorTranslate(errorId as string);
          showFailedMessage(errorMsg);
        }
      }
      getInfo();
    });
}
function dialogClose(reason: boolean) {
  dialogVisible.value = false;
}
function uploadDialogFun() {
  dialogVisible.value = true;
}
function fileChange(value: string) {
  uploadBtnDisable.value = true;
}

function copy(target: any, source: any) {
  for (const item of target) {
    for (const key of source) {
      if (item.id === key.id) {
        item.checked = key.checked;
        break;
      }
    }
  }
}
function _resetLogType(arr: { checked: any; id: any }[]) {
  const result: any[] = [];
  arr.forEach((item: { checked: any; id: any }) => {
    if (item.checked) {
      result.push(item.id);
    }
  });
  return result;
}
function setLog() {
  return [
    {
      id: 'OperationLog',
      text: 'OPERATE_LOG',
      checked: false,
    },
    {
      id: 'SecurityLog',
      text: 'SERCURITY_LOG',
      checked: false,
    },
    {
      id: 'EventLog',
      text: 'EVENT_LOG',
      checked: false,
    },
    {
      id: 'IntrusionDetectionLog',
      text: 'INTRUSION_DETECTION_LOG',
      checked: false,
    },
    {
      id: 'SysComLog',
      text: 'SYS_COM_LOG',
      checked: false,
    },
    {
      id: 'BmcComLog',
      text: 'BMC_COM_LOG',
      checked: false,
    },
    {
      id: 'DiagnosticLog',
      text: 'DIAGNOSTIC_LOG',
      checked: false,
    },
    {
      id: 'ChipLog',
      text: 'CHIP_LOG',
      checked: false,
    },
  ];
}
function _setChecked(arr: any, selected: [] = []) {
  for (const key of arr) {
    for (const item of selected) {
      if (key['id'] === item) {
        key.checked = true;
        break;
      }
    }
  }
}
const tempTableData: any[] = [];
// 表格操作
function tableChange(event: any) {
  loading(true);
  switch (event.key) {
    case 'save':
      event.value.isEdit = false;
      save(event.value);
      break;
    case 'cancel':
      cancel(event.value);
      event.value.isEdit = false;
      break;
    case 'edit':
      tempTableData[event.value.num - 1] = {
        num: event.value.num,
        statusValue: event.value.statusValue,
        serviceAddr: event.value.serviceAddr,
        port: event.value.port,
        itemSelect: event.value.itemSelect,
        LogType: setLog(),
      };
      copy(tempTableData[event.value.num - 1].LogType, event.value.LogType);
      event.value.isEdit = true;
      loading(false);
      break;
    case 'test':
      // 若参数未保存，弹框提示。
      if (!syslogBtn.value) {
        loading(false);
        commonDialogRef.value.show();
      } else {
        test(event.value);
      }
      break;
    default:
      return;
  }
}
interface saveType {
  num: number;
  statusValue: any;
  serviceAddr: any;
  port: string | number | null;
  LogType: any;
  logType: any;
  itemSelect: string | undefined;
}

// 保存
function save(data: saveType) {
  const params = {
    SyslogServerList: [
      {
        ID: data.num - 1,
        Enabled: data.statusValue,
        IP: data.serviceAddr,
        Port: parseInt(data.port as string, 10),
        LogType: _resetLogType(data.LogType),
      },
    ],
  };
  sysLogSave(params)
    .then(res => {
      const response = res['data'] as any;
      let syslogServerList = response?.SyslogServerList;
      if (response.error) {
        showFailedMessage();
        syslogServerList = response['data']?.SyslogServerList;
      } else {
        showSuccessMessage();
      }
      const memberId = data.num - 1;
      if (syslogServerList && syslogServerList.length > 0) {
        syslogServerList.forEach(
          (item: { ID: any; Enabled: any; IP: any; Port: number; LogType: any }) => {
            if (Number(item.ID) === Number(memberId)) {
              data.statusValue = item.Enabled;
              data.serviceAddr = item.IP;
              data.port = item.Port === 0 ? null : item.Port;
              copy(data.LogType, item.LogType);
              data.logType = setLog();
              _setChecked(data.logType, item.LogType);
              data.itemSelect = _setLogTypeSelect(item.LogType);
            }
          },
        );
      }
      loading(false);
    })
    .catch(error => {
      loading(false);
      showFailedMessage();
    });
}
// 取消
function cancel(data: {
  port: any;
  num: number;
  statusValue: any;
  serviceAddr: any;
  LogType: any;
  itemSelect: any;
}) {
  data.port = tempTableData[data.num - 1].port;
  data.statusValue = tempTableData[data.num - 1].statusValue;
  data.serviceAddr = tempTableData[data.num - 1].serviceAddr;
  data.port = tempTableData[data.num - 1].port;
  copy(data.LogType, tempTableData[data.num - 1].LogType);
  data.itemSelect = tempTableData[data.num - 1].itemSelect;
  tempTableData[data.num - 1] = null;
  loading(false);
}
// 测试
function test(data: { num: number }) {
  const params = {
    ID: Number(data.num - 1),
  };
  sysLogSendTest(params)
    .then(res => {
      loading(false);
      showSuccessMessage(traduction('ALARM_REPORT_TEST_MESSAGE'));
    })
    .catch(error => {
      loading(false);
      const code = error?.data?.error[0]?.code;
      if (code) {
        const errorMessage = code + '.errorMessage';
        showFailedMessage(traduction(errorMessage));
        return;
      }
      showFailedMessage();
    });
}

function commonDialogClose(reason: boolean) {
  commonDialogRef.value.hide();
}

function redirect(): void {
  $router.push('/navigate/user/certificate/ca-certificate-list');
}

function callbackSuccess(redirectType: number): void {
  if (redirectType === 1) {
    redirectComp.value.hide();
    $router.push('/navigate/user/certificate/ca-certificate-list');
  } else if (redirectType === 2) {
    redirectSslComp.value.hide();
    $router.push('/navigate/user/certificate/ssl-certificate');
  }
}

function redirectSsl(): void {
  $router.push('/navigate/user/certificate/ssl-certificate');
}

function callbackFail(redirectType: number): void {
  if (redirectType === 1) {
    redirectComp.value.hide();
  } else if (redirectType === 2) {
    redirectSslComp.value.hide();
  }
}

onMounted(() => {
  getInfo();
});
</script>

<style lang="scss" scoped>
#syslog {
  margin-right: 24px;
  height: calc(100% - 104px);
}
#syslogCerItem {
  height: 16px;
  :deep(.el-form-item__label-wrap) {
    .el-form-item__label {
      padding-top: 0px;
    }
  }
}
#localCer {
  height: 16px;
  :deep(.el-form-item__label-wrap) {
    .el-form-item__label {
      padding-top: 0px;
    }
  }
}
.top-title {
  font-size: 16px;
  color: var(--o-text-color-primary);
  line-height: 24px;
  margin-bottom: 16px;
}
.syslog-info {
  background-color: var(--o-bg-color-base);
  border-radius: 4px;
  padding: 24px;
  margin-bottom: 16px;
  .el-select {
    width: 320px;
  }
}
.syslog-syntax {
  background-color: var(--o-bg-color-base);
  border-radius: 4px;
  padding: 24px;
}
#syslogAlert {
  font-size: 12px;
  color: var(--o-color-major);
  letter-spacing: 0;
  line-height: 16px;
  margin-left: 8px;
}
.cer-item {
  :deep(.el-form-item__content) {
    display: flex;
    justify-content: space-between;
  }
  .cer-box {
    width: calc((100% - 16px) / 2);
    display: flex;
    flex-direction: column;
    &.full-width {
      width: 100%;
    }
  }
  .local-cer {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    min-height: 100%;
  }
  .upload-dialog-label {
    font-size: 12px;
    color: var(--o-text-color-secondary);
    letter-spacing: 0;
    line-height: 32px;
    margin-right: 24px;
  }
}
.cer-file-upload {
  .el-form-item__content {
    position: relative;
    #uploadx {
      position: absolute;
      right: 24px;
      top: -4px;
    }
  }
}
.table-title {
  font-size: 16px;
  color: var(--o-text-color-primary);
  line-height: 24px;
  margin-bottom: 16px;
}
.syslog-btns {
  margin-bottom: 0;
}
:deep(.small-item) {
  height: 16px;
  .el-form-item__label {
    padding-top: 0;
    padding-bottom: 0;
  }
  .el-form-item__content {
    line-height: 16px;
  }
  .el-radio {
    height: 16px;
  }
  .el-radio__label {
    color: var(--o-text-color-secondary);
  }
}
</style>
